from django.shortcuts import render
from django.shortcuts import HttpResponse
from web_models import models
import json
import datetime
# Create your views here.
def url_count(request):

    if request.method == "POST":
        data = request.POST.get("data")

        data = json.loads(data)


        urls = data["urls"]

        port = data["port"]
        host = data["host"]
        domain = models.Domain.objects.filter(port=port,host=host).values("domain")[0]["domain"]


        access_time = data["access_time"]
        data.pop("urls")
        data.pop("port")
        urls = json.loads(urls)

        sql_urls_count = models.UrlCount.objects.filter(access_time=access_time).count()

        if sql_urls_count == 0:
            for url in urls:

                count = urls[url]
                models.UrlCount.objects.create(url=url,domain=domain,count=count,**data)
        else:

            for url in urls:
                old_count = models.UrlCount.objects.filter(domain=domain,url=url,access_time=access_time).count()
                if old_count == 0:
                    count = urls[url]
                    models.UrlCount.objects.create(url=url,domain=domain,count=count,**data)
                else:
                    count = urls[url] + old_count
                    models.UrlCount.objects.filter(domain=domain,url=url,access_time=access_time).update(count=count)



        return HttpResponse('ok')
    if request.method == "GET":

        def get_access_time(day):
            now_time = datetime.datetime.now()
            yes_time = now_time + datetime.timedelta(days=-day)
            access_time = yes_time.strftime('%Y-%m-%d')
            return access_time

        get_day = int(request.GET.get("day",1))
        import os
        os.op

        print(get_day)

        access_time = get_access_time(get_day)
        print(access_time)
        data = models.UrlCount.objects.filter(access_time=access_time).values("domain","url","count")
        d = []
        for i in data:

            d.append(i)

        d = json.dumps(d)
        return HttpResponse(d)


